<template>
  <div>
    <!-- 查询区域 -->
    <div class="card" style="margin-bottom: 5px">
      <el-card>
        <el-input
          style="width: 200px; margin-right: 10px"
          v-model="coach.id"
          placeholder="请输入ID查询"
          prefix-icon="Search"
        />
        <el-button type="primary" @click="load">查 询</el-button>
        <el-button type="warning" @click="reset">重 置</el-button>
      </el-card>
    </div>

    <!-- 操作按钮 -->
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" @click="handleAdd">新 增</el-button>
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 表格 -->
    <div class="card" style="margin-bottom: 5px">
      <el-table
        :data="coach.tableData"
        border
        style="width: 100%"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>

        <el-table-column label="编号" type="index" width="60"></el-table-column>
        <el-table-column label="eid" prop="eid">
          <template #default="scope">
            <router-link
              :to="{ name: 'a_employee_with_eid', params: { eid: scope.row.eid } }"
              style="color: #409EFF; cursor: pointer;"
            >{{ scope.row.eid }}</router-link>
          </template>
        </el-table-column>
        <el-table-column label="简介1" prop="text1"></el-table-column>
        <el-table-column label="简介2" prop="text2"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              icon="Edit"
              size="small"
              @click="handleEdit(scope.row)"
              >编 辑</el-button
            >
            <el-button
              type="danger"
              icon="Delete"
              size="small"
              @click="handleDelete(scope.row)"
              >删 除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: right;">
        <el-pagination
          @size-change="load"
          @current-change="load"
          v-model:current-page="coach.pageNumber"
          v-model:page-size="coach.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="coach.total"
          background
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="coach.form.eid ? '编辑教练' : '新增教练'" v-model="coach.formVisible" width="500">
      <el-form :model="coach.form" style="padding-right: 50px; padding-top: 20px;">
        <el-form-item label="教练ID" label-width="80px">
          <el-input v-model.number="coach.form.eid" placeholder="请输入教练ID" />
        </el-form-item>
        <el-form-item label="简介1" label-width="80px">
          <el-input v-model="coach.form.text1" placeholder="请输入简介1" />
        </el-form-item>
        <el-form-item label="简介2" label-width="80px">
          <el-input v-model="coach.form.text2" placeholder="请输入简介2" type="textarea" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="coach.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete } from '@element-plus/icons-vue'

const course = reactive({
  selectedRows: []
})

const coach = reactive({
  id: '',
  pageNumber: 1,
  pageSize: 10,
  total: 0,
  tableData: [],
  formVisible: false,
  form: {}
})

// 加载数据
const load = () => {
  request.get('/v1/admin/selectPage', {
    params: {
      tableName: 'coach_introduction',
      id: coach.id,
      pageNum: coach.pageNumber,
      pageSize: coach.pageSize
    }
  }).then(res => {
    if (res.state === 2001) {
      coach.tableData = res.data.list || []
      coach.total = res.data.total || 0
    } else {
      coach.tableData = []
      coach.total = 0
    }
  }).catch(error => {
    console.error('请求失败:', error)
    coach.tableData = []
    coach.total = 0
  })
}

// 重置搜索条件
const reset = () => {
  coach.id = ''
  load()
}

// 新增方法：清空 eid 输入，由用户手动填写
const handleAdd = () => {
  coach.form = {
    eid: null,
    text1: '',
    text2: ''
  }
  coach.formVisible = true
}

// 编辑方法：填充已有 eid + 文本
const handleEdit = row => {
  coach.form = { ...row }
  coach.formVisible = true
}

// 删除方法
const handleDelete = row => {
  ElMessageBox.confirm('确定要删除该教练吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete('/v1/admin/delete', {
      data: {
        tableName: 'coach_introduction',
        id: row.eid
      }
    }).then(res => {
      if (res.state === 2001) {
        ElMessage({ message: '删除成功', type: 'success' })
        load()
      } else {
        ElMessage({ message: '删除失败', type: 'error' })
      }
    }).catch(error => {
      console.error('请求失败:', error)
      ElMessage({ message: '请求失败，请检查网络或服务器', type: 'error' })
    })
  }).catch(() => {})
}

// 保存逻辑：新增 / 更新
const save = () => {
  const eid = coach.form.eid
  if (!eid) {
    ElMessage({ message: '请输入有效的教练ID', type: 'warning' })
    return
  }

  // 第一步：检查员工是否存在且是教练
  request.get('/v1/admin/checkCoachExist', {
    params: { eid }
  }).then(res => {
    if (res.state === 2001 && res.data.exists) {
      // 第二步：检查是否已有该教练简介
      return request.get('/v1/admin/checkCoachIntroductionExist', {
        params: { eid }
      })
    } else {
      ElMessage({ message: '员工不存在或不是教练', type: 'error' })
      throw new Error('校验失败')
    }
  }).then(resIntro => {
    const introExists = resIntro?.data?.exists || false
    const method = introExists ? 'put' : 'post'
    const url = introExists ? '/v1/admin/update' : '/v1/admin/add'

    // 提交数据
    const payload = {
      tableName: 'coach_introduction',
      data: {
        eid: coach.form.eid,
        text1: coach.form.text1,
        text2: coach.form.text2
      }
    }

    return request[method](url, payload)
  }).then(res => {
    if (res.state === 2001) {
      ElMessage({
        message: coach.form.eid ? '编辑成功' : '新增成功',
        type: 'success'
      })
      coach.formVisible = false
      load()
    } else {
      ElMessage({
        message: coach.form.eid ? '编辑失败' : '新增失败',
        type: 'error'
      })
    }
  }).catch(error => {
    console.error('请求失败:', error)
    ElMessage({ message: '请求失败，请检查网络或服务器', type: 'error' })
  })
}

// 多选处理
const handleSelectionChange = rows => {
  course.selectedRows = rows
}

// 批量删除
const handleBatchDelete = () => {
  if (course.selectedRows.length === 0) {
    ElMessage({ message: '请选择要删除的记录', type: 'warning' })
    return
  }

  const ids = course.selectedRows.map(row => row.eid)

  ElMessageBox.confirm('确定要删除这些课程简介吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    request.delete('/v1/admin/batchDelete', {
      data: {
        tableName: 'coach_introduction',
        ids: ids
      }
    }).then(res => {
      if (res.state === 2001) {
        ElMessage({ message: '批量删除成功', type: 'success' })
        load()
      } else {
        ElMessage({ message: '批量删除失败', type: 'error' })
      }
    }).catch(error => {
      console.error('请求失败:', error)
      ElMessage({ message: '请求失败，请检查网络或服务器', type: 'error' })
    })
  }).catch(() => {
    // 取消操作
  })
}

// 初始化加载
load()
</script>

<style scoped>
.card {
  margin-bottom: 10px;
}
</style>
